<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import { ListToTree } from '@/utils/listToTree'
import DepartmentService from '@/api/department'
import EmployeeService from '@/api/employee'
import FileSaver from 'file-saver'
import ImportExcel from './components/ImportExcel.vue'
import { useRouter } from 'vue-router'

// 部门树形节点
const departments = ref([] as any)
const defaultProps = {
  label: 'name',
  children: 'children'
}
const queryParams = ref({
  departmentId: null,
  page: 1,
  pagesize: 10,
  keyword: ''
})
const treeRef = ref()
// 员工列表
const employeeList = ref([] as any)
// 查询员工总数
const total = ref(0)
// excel弹层
const showExcelDialog = ref(false)

const router = useRouter()

const getDpartment = async () => {
  var res: any = await DepartmentService.getDepartmentService()
  departments.value = ListToTree(res, 0)
  queryParams.value.departmentId = departments.value.find((item: any) => item.pid == 0).id
  // 设置默认选中节点
  // 树组件渲染是异步的，等到更新完毕后才能拿到组件方法，再选中
  nextTick(() => {
    treeRef.value.setCurrentKey(queryParams.value.departmentId)
  })
  await getEmployeeList()
}
getDpartment()

const getEmployeeList = async () => {
  var res: any = await EmployeeService.getEmployeeListService(queryParams.value)
  employeeList.value = res.rows
  total.value = res.total
}
// 切换节点
const selectNode = async (node: any) => {
  queryParams.value.departmentId = node.id
  queryParams.value.page = 1 // 设置第一页
  await getEmployeeList()
}
// 换页
const changePage = async (newPage: any) => {
  queryParams.value.page = newPage
  await getEmployeeList()
}
// 输入框事件
let timer: any = null
const changValue = () => {
  // 防抖：单位时间内只执行最后一次
  clearTimeout(timer)
  timer = setTimeout(() => {
    queryParams.value.page = 1
    getEmployeeList()
  }, 1000)
}
// 导出员工
const exportExcel = async () => {
  const res: any = await EmployeeService.exportEmployeeService()
  // 使用第三方库，将blbo文件下载到本地（file-saver)
  // FileSaver.saveAs(blob对象，文件名称)
  FileSaver.saveAs(res, '员工信息表.xlsx')
}
// 删除
const confirmDelete = async (id: any) => {
  await EmployeeService.deleteEmployeeService(id)
  getEmployeeList()
}

// 弹层
const showDialog = ref(false)
const roleList = ref([] as any)
const roleIds = ref([] as any)
const currentUserId = ref(null as any)
const btnRole = async (id: any) => {
  currentUserId.value = id
  var res: any = await EmployeeService.getEnableRoleListService()
  roleList.value = res
  var resRole: any = await EmployeeService.getEmployeeDetailService(id)
  roleIds.value = resRole.roleIds
  console.log(resRole.roleIds)

  showDialog.value = true
}
const btnRoleOk = async () => {
  await EmployeeService.assignRoleService({
    id: currentUserId.value,
    roleIds: roleIds.value
  })
  ElMessage.success('分配用户角色成功')
  showDialog.value = false
}
</script>

<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="treeRef"
          node-key="id"
          :data="departments"
          :props="defaultProps"
          default-expand-all
          expand-on-click-node
          highlight-current
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button
            size="small"
            type="primary"
            v-permission="'add-employee'"
            @click="router.push('/employee/detail')"
            >添加员工</el-button
          >
          <el-button size="small" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="small" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="employeeList">
          <el-table-column align="center" label="头像" prop="staffPhoto">
            <template #default="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30"></el-avatar>
              <span class="username" v-else>{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" prop="mobile" sortable />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" width="280px">
            <template #default="{ row }">
              <!-- 路由传参！！！！ -->
              <el-button
                size="small"
                text
                @click="router.push({ name: `employeeDetail`, params: { id: row.id } })"
                >查看</el-button
              >
              <el-button size="small" text @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm @confirm="confirmDelete(row.id)" title="确定要删除吗?">
                <template #reference>
                  <el-button size="small" text>删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row align="middle" type="flex" justify="end" style="height: 60px">
          <el-pagination
            layout="total, prev, pager, next"
            :total="total"
            :cuurent-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>
    <!-- 放置导入组件 -->
    <!-- Vue3 => v-model :modelValue 和 @update:modelValue 的简写 -->
    <import-excel v-model="showExcelDialog" @uploadSuccess="getEmployeeList" />
    <!-- 弹层内容 -->
    <el-dialog v-model="showDialog" title="分配角色">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id">{{
          item.name
        }}</el-checkbox>
      </el-checkbox-group>
      <!-- 确定和取消 -->
      <template #footer>
        <el-row type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="small" @click="btnRoleOk">确定</el-button>
            <el-button size="small" @click="showDialog = false">取消</el-button>
          </el-col>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
